<?php

class Products_Form_Product extends Zend_Form 
{
    
    /**
     * Initialize form (used by extending classes)
     *
     * @return void
     */
    public function init()
    {
        $element = new Zend_Form_Element_Hidden('id');
        $this->addElement($element);
        
        
        $element = new Zend_Form_Element_Text('name');
        $element
            ->setLabel('Наименование Продукта')
            ->setRequired()
            ->addFilter('StringTrim')
            ->addValidator('StringLength', false, array(3, 128))
            ;
        $this->addElement($element);
        
        require_once APPLICATION_PATH . '/modules/products/filters/Double.php';
        $filter = new Products_Filter_Double;
        foreach ($this->_getComponents() as $code => $name) {
            $element = new Zend_Form_Element_Text('component_' . $code);
            $element
                ->setLabel($name)
                //->setRequired()
                ->addFilter('StringTrim')
                ->addFilter($filter)
                ;
            $this->addElement($element);
        }
        
        $element = new Zend_Form_Element_Submit('submit');
        $element
            ->setLabel('Сохранить')
            ->setIgnore(true)
            ;
        $this->addElement($element);
    }
    
    /**
     * Retrieve all form element values
     *
     * @param  bool $suppressArrayNotation
     * @return array
     */
    public function getValues($suppressArrayNotation = false)
    {
        $data = array();
        $values = parent::getValues($suppressArrayNotation);
        
        foreach ($values as $key => $value) {
            if (false !==strpos($key, 'component_')) {
                $data['components'][] = array
                (
                    'component_code' => substr($key, -1, 1), 
                    'value' => $value, 
                );
            } else {
                $data[$key] = $value;
            }
        }
        
        return $data;
    }
    
    /**
     * Validate the form
     *
     * @param  array $data
     * @return boolean
     */
    public function isValid($data)
    {
        $validator = new FinalView_Validate_Db_NoRecordExists('Products', 'name');
        $validator->setMessage('%value% - продукт уже сохранен в БД', 
            FinalView_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND);
        if ($data['id']) {
            $validator->setExclude(array('id' => $data['id']));
        }
        $element = $this->getElement('name');
        $element->addValidator($validator);
        
        
        return parent::isValid($data);
    }
    
    private function _getComponents() 
    {
        $model = new Components;
        return $model->getOptions();
    }
    
}